package com.ml.elasticsearch.api.index;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 索引基本操作，javaAPI版
 *
 * @author xr-8
 * @date 2023-04-16
 * @time 23:03
 */
@Service
public class IndexApi {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     */
    public void creatIndex() throws IOException {
        // 创建索引 - 请求对象
        CreateIndexRequest request = new CreateIndexRequest("user2");
        // 发送请求，获取响应
        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        // 响应状态
        System.out.println("操作状态 = " + response.isAcknowledged());
    }

    /**
     * 查看索引,先检查是否存在
     */
    public void getIndex() throws IOException {
        // 查询索引 - 请求对象
        GetIndexRequest request = new GetIndexRequest("user2");
        // 查看索引是否存在
        Boolean responseExist = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        // 操作结果
        System.out.println("responseExist:"+responseExist);
        if (responseExist) {
            // 发送请求，获取响应
            GetIndexResponse response = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
            // 操作结果
            System.out.println("aliases:"+response.getAliases());
            System.out.println("mappings:"+response.getMappings());
            System.out.println("settings:"+response.getSettings());
        }
    }


    /**
     * 删除索引
     */
    public void deleteIndex() throws IOException {
        // 删除索引 - 请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("user2");
        // 发送请求，获取响应
        AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        // 操作结果
        System.out.println("操作结果:" + response.isAcknowledged());
    }

    /**
     * 更新索引: ElasticSearch中索引不能修改
     */
    @Deprecated
    public void updateIndex() throws IOException {

    }

}
